<template>
  <div class="search_wapper">
    <!-- 顶部搜索栏目 -->
    <div class="search">
      <div class="search_bg">
        <van-icon name="search" size="0.18rem" />
        <form action="javascript:;" ref="searchFrom">
          <input type="search" v-model="sarchValue" placeholder="请输入任务名称或编号" />
        </form>         
      </div>
    </div>

    <!-- 高级选项内容 -->
    <div class="content">
      <div class="content_time">
        <div class ="content_time_title">完成时间</div>
        <div class ="content_time_content">
          <span @click="handleShowDataTimer('start')">{{pickTime.startTime}}</span>
          -          
          <span @click="handleShowDataTimer('end')">{{pickTime.endTime}}</span>
        </div>
        <div class ="content_time_select">
          <van-dropdown-menu>
            <van-dropdown-item 
              v-model="dateTypeValue" 
              :options="dateTypeList" 
              @change="handleDateChange"/>
          </van-dropdown-menu>
        </div>
        <div class ="content_time_clear" @click="handleClearTime">
          <i class="iconfont iconqingchushujuku"></i>
        </div>
      </div>
      <van-collapse 
        v-model="activeNames"
        :border="false">
        <van-collapse-item title="任务关系" name="1">
          <gzhb-checkbox :data="Relationship"></gzhb-checkbox>
        </van-collapse-item>
        <van-collapse-item title="任务状态" name="2">
          <gzhb-checkbox :data="stautsList"></gzhb-checkbox>
        </van-collapse-item>
        <!-- <van-collapse-item title="任务年份" name="3">
          <gzhb-checkbox :isSingle="true" :data="dateTypeList"></gzhb-checkbox>
        </van-collapse-item> -->
        <van-collapse-item v-if="typeList.length" title="任务类型" name="3">
          <gzhb-checkbox :data="typeList"></gzhb-checkbox>
        </van-collapse-item>
        <van-collapse-item v-if="labelList.length" title="任务标签" name="4">
          <gzhb-checkbox :data="labelList"></gzhb-checkbox>
        </van-collapse-item>
      </van-collapse>
    </div>

    <div class="bottom_brn" @click="handleJump2List">搜索</div>

    <!-- 时间选择 -->
    <van-popup v-model="pickTime.show" position="bottom">
      <van-datetime-picker
        v-model="pickTime.time"
        type="date"
        @cancel="pickTime.show = false"
        @confirm="pickTimeConfirm"/>
    </van-popup>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  name: 'search',
  data () {
    return {
      activeNames: ['1','2','3','4'],
      timerStatus:'',
      // 名称或编码
      sarchValue: '',
      // 日期
      pickTime: {
        show: false,
        time: new Date(),
        startTime: '',
        endTime: ''
      },      
      // 关系
      Relationship:[
        { name: '我承办的任务', checked: true, code: 1},
        { name: '我关注的任务', checked: false, code: 2},
        { name: '我验收的任务', checked: false, code: 3}
      ],
      // 状态
      stautsList:[
        { name: '已终止', checked: false, code:'TT'},
        { name: '逾期完成', checked: false, code:'GG'},
        { name: '按期完成', checked: false, code:'FF'},
        { name: '逾期', checked: true, code:'LL'},
        { name: '即将到期', checked: true, code:'YY'},
        { name: '正常执行', checked: true, code:'EE'},
        { name: '未开始', checked: false, code:'SS'},
      ],
      // 年份( datetype 年 : 1 季 : 4 月 :2 周 : 3 )
      // dateTypeList:[
      //   { name: '所有', checked: false, code: ''},
      //   { name: '本年', checked: true, code: '1'},
      //   { name: '本季', checked: false, code: '4'},
      //   { name: '本月', checked: false, code: '2'},
      //   { name: '本周', checked: false, code: '3'}
      // ],
      dateTypeList: [
        { text: '所有', value: '' },
        { text: '本年', value: '1' },
        { text: '本季', value: '4' },
        { text: '本月', value: '2' },
        { text: '本周', value: '3' }
      ],
      dateTypeValue: '1',
      // 类型
      typeList:[],
      // 标签
      labelList:[],

      placeholder: '请输入任务名称或编号3'
    }
  },
  created () {
    this.timeFilter(this.dateTypeValue)

    let searchForm = JSON.parse(sessionStorage.getItem('searchForm'))
    
    //（如果有搜索记录，则匹配之前的搜索记录）
    if(searchForm){
      this.sarchValue = searchForm.sarchValue
      this.Relationship = [...Object.assign(this.Relationship, this.Relationship, searchForm.Relationship)]
      this.stautsList = [...Object.assign(this.stautsList, this.stautsList, searchForm.stautsList)]
      this.dateTypeValue = searchForm.dateTypeValue
      Object.assign(this.pickTime, this.pickTime, searchForm.pickTime)
    }
    
    // 类型（如果有搜索记录，则匹配之前的搜索记录）
    this.typeList = JSON.parse(localStorage.getItem('typeList')) || []
    this.typeList.forEach(item=>{
      if(searchForm){
        searchForm.typeList.forEach( entris=>{
          if (item.name === entris.name){
            item.checked = entris.checked
          }
        })
      }else{
        item.checked = false
      }
    })
    
    // 标签（如果有搜索记录，则匹配之前的搜索记录）
    this.labelList = JSON.parse(localStorage.getItem('labels')) || []
    this.labelList.forEach(item=>{
      if(searchForm){
        searchForm.labelList.forEach( entris=>{
          if (item.name === entris.name){
            item.checked = entris.checked
          }
        })
      }else{
        item.checked = false
      }
    })
  },
  mounted () {
    // 点击软键盘搜索按钮
    this.$refs.searchFrom.addEventListener('submit', function () {
      this.placeholder = ''
    })    
  },
  methods: {
    // 跳转搜索
    handleJump2List(){
      let RelationshipFilter = []
      let stautsListFilter = []
      let typeListFilter = []

      // 关系
      this.Relationship.forEach(item => {
         if(item.checked) RelationshipFilter.push(item.code)
      })
      // 状态
      this.stautsList.forEach(item => {
         if(item.checked) stautsListFilter.push(item.code)
      })
      // 类型
      this.typeList.forEach(item => {
         if(item.checked) typeListFilter.push(item.id)
      })

      // 根据不同的关系，跳转到列表的时候，对应不同得tab标签
      let activeTab = 'first'
      if(RelationshipFilter.includes(3) && RelationshipFilter.length === 1){
        activeTab = 'second'
      }

      // 保存搜索记录
      sessionStorage.setItem('searchForm', JSON.stringify({
        sarchValue: this.sarchValue,
        pickTime: this.pickTime,
        Relationship: this.Relationship,
        stautsList: this.stautsList,
        dateTypeValue : this.dateTypeValue,
        typeList: this.typeList,
        labelList: this.labelList,
      }))

      let obj = {
        start: this.pickTime.startTime !== '开始时间' ? this.pickTime.startTime : '' ,
        end: this.pickTime.endTime !== '结束时间' ? this.pickTime.endTime : '' ,
        name: this.sarchValue,
        principal: RelationshipFilter.join(','),
        stat: stautsListFilter,
        lxLines: typeListFilter
      } 

      // 当有自定义时间的时候，不需要年月日的时间选择字段
      if(this.pickTime.startTime === '开始时间' && this.pickTime.endTime === '结束时间'){
        obj.datetype = this.dateTypeValue
      }
     
      // 跳转任务列表----------------------------------------------------------------------------
      this.$store.commit('SET_IS_FIRST_COME', false)
      this.$router.push({name: 'taskList', params:{
        activeTab,
        isSearchUpdata: true,
        searchForm: obj        
      }})
    },

    // 日期选择
    handleShowDataTimer(status){
      this.pickTime.show = true
      this.timerStatus = status
    },
    
    // 日期确认
    pickTimeConfirm(){
      this.pickTime.show = false
      if(this.timerStatus === 'start'){        
        this.pickTime.startTime = moment(this.pickTime.time).format('YYYY-MM-DD')
      } else {
        this.pickTime.endTime = moment(this.pickTime.time).format('YYYY-MM-DD')
      }
    },

    timeFilter(type){
      let time = []
      if(type === '1'){
        time = this.getCurrYear()        
      } else if(type === '4'){
        time = this.getCurrQuarter()        
      } else if(type === '2'){
        time = this.getCurrMonthDays()          
      } else if(type === '3'){
        time = this.getCurrWeekDays()          
      } else {
        time = ['开始时间', '结束时间']
      }

      this.pickTime.startTime = time[0]
      this.pickTime.endTime = time[1]
    },

    // 本年、本季、本月、本周时间选中
    handleDateChange(value){
      this.timeFilter(value)
    },

    // 重置日期
    handleClearTime(){
      this.pickTime.startTime = '开始时间'
      this.pickTime.endTime = '结束时间'
    },

    //获取本年
    getCurrYear(){
      let date = []      
      let start = moment().startOf('year').format('YYYY-MM-DD')      
      let end = moment().endOf('year').format('YYYY-MM-DD')
      date.push(start)
      date.push(end)
      return date
    },
    // 当前季度
    getCurrQuarter(){
      let date = []
      let start = moment().startOf('quarter').format('YYYY-MM-DD')
      let end = moment().endOf('quarter').format('YYYY-MM-DD')
      date.push(start)
      date.push(end)
      return date
    },
    // 获取当前月的开始结束时间
    getCurrMonthDays(){
      let date = []
      let start = moment().startOf('month').format('YYYY-MM-DD')
      let end = moment().endOf('month').format('YYYY-MM-DD')
      date.push(start)
      date.push(end)
      return date
    },
    // 获取当前周的开始结束时间，周日到周六
    getCurrWeekDays(){
      let date = []
      let start = moment().startOf('week').format('YYYY-MM-DD')
      let end = moment().endOf('week').format('YYYY-MM-DD')
      date.push(start)
      date.push(end)
      return date
    }

  }
}
</script>

<style lang="less">
  .content /deep/{
    flex: 1;
    overflow: hidden;
    overflow-y: scroll;

    // 选择时间
    .content_time{
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 0 0.16rem;
      height: 0.45rem;
      border-bottom: 0.05rem solid #ebedf0;
      .content_time_title{
        color: #9a9a9a;
        font-size: 0.14rem;
      }
      .content_time_content{
        flex: 1;
        display: flex;
        justify-content: center;
        align-items: center;
        span{
          display: inline-block;
          padding: 0.04rem 0.05rem;
          border-radius: 0.15rem;
          min-width: 0.9rem;
          min-height: 0.24rem;
          font-size: 0.14rem;
          text-align: center;
          background-color: #f7f7f7;
        }
      }
      .content_time_select{
        width: 0.54rem;
        height: 0.25rem;
        font-size: 0.15rem;
        .van-dropdown-menu{
          height: 0.26rem;
          border-radius: 0.5rem;
          background-color: #def1ff;
          overflow: hidden;
          .van-dropdown-menu__title{
            padding-left: 0;
            color: #0089f1;
            // &::after{
            //   display: none;
            // }
          }
        }
      }
      .content_time_clear{
        display: flex;
        justify-content: center;
        align-items: center;
        margin-left: 0.06rem;
        border-radius: 0.15rem;
        width: 0.25rem;
        height: 0.25rem;
        color: white;
        font-size: 0.15rem;
        i{  
          color: #0089f1;
          font-size: 0.24rem;
        }
      }
    }

    //任务
    .van-cell__title{
      color: #9a9a9a;
    }
    .van-cell{
      padding-bottom: 0;
    }
    .van-collapse-item__content{
      padding-top: 0;
    }
    .van-hairline--top::after {
      border-top-width: 0.1rem;
    }
    .van-cell:not(:last-child)::after {
      border-bottom: none;
    }
  }
</style>

<style lang="less" scoped>
.search_wapper{
  display: flex;
  flex-direction: column;
  height: 100%;
  //搜索
  .search{
    padding: 0.05rem 0.07rem;
    height: 0.4rem;
    color: #9a9a9a;
    background-color: #0089f1;
    .search_bg{
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 0.1rem;
      height: 0.3rem;      
      background-color: white;
      input{
        color: #000;
      }
      span{
        font-size: 0.16rem;
        line-height: 0.17rem;
      }
    }
  }

  // 底部
  .bottom_brn{
    display: flex;
    justify-content: center;
    align-items: center;
    height: 0.4rem;
    color: white;
    background-color: #ffba00;
  }

  // 时间选择
  .datetime_wapper{
    position: fixed;
  }
}
</style>